<?php
class SupplierRetrievesController extends AppController {
    var $name = 'SupplierRetrieves';

    var $viewPath = 'suppliers/returns/supplier_retrieves';

    var $pageTitle = 'Customer Return Information';

    /**
     * SRH => SupplierRetrieveHead
     * SR => SupplierRetrieve
     * @array model ที่ใช้งาน
     */
    var $uses = array('SRH','SR', 'CRtSH', 'Product', 'Supplier', 'RunningNo', 'CRS', 'CRtS', 'ProductSerial', 'UserCoH', 'RS', 'CustProductSite');

    var $paginate = array(
            'SRH' => array(
                            'order' => 'SRH.id DESC'
            )
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'main_supplier_returns');
        $this->set('tabMenu', 'tabmenus/supplier/returns');
    }

    function display() {
        parent::display('SRH');
        $this->paginate['SRH']['contain'] = array('Customer', 'Site', 'CRtSH', 'RS');

        $this->_checkSupplier('SRH');
        $this->_checkCustomerOnHand('SRH');

        $this->_paging('SRH');
    }

    function save() {
        $is_success = true;
        $CRtSh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            $this->SRH->id = $this->data['SRH']['id'];
            $is_success = $this->SRH->saveField('remark', $this->data['SRH']['remark']);
            $is_success &= $this->SRH->saveField('collector_id', $this->Auth->user('id'));
        }

        if ($is_success) {
            $CRtSh_id = $this->SRH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['SR'] = null;
        $this->setAction('view', $CRtSh_id);
    }

    function _save_return() {
        $CRtSh_id = null;
        // ตรวจสอบว่ามีรายการเข้ามาหรือไม่
        $is_success = true;
        if (!empty($this->data['SRH']['cust_return_to_supplier_head_id'])) {

            $this->SRH->query("BEGIN");
            ;

            // กำหนดข้อมูล CRtSH Return Head
            // Generate return no
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::CUST_RETURN_TYPE, $year, null, 5);
            $this->data['SRH']['retrieve_no'] = RunningNo::CUST_RETURN_TYPE . $year . '1' . $runno;
            $this->data['SRH']['collector_id'] = $this->Auth->user('id');
            $this->data['SRH']['supplier_id'] = $this->Auth->user('supplier_id');

            if($this->SRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                $this->CRtSH->id = $this->data['SRH']['cust_return_to_supplier_head_id'];
                $this->CRtSH->saveField('vendor_document_no', $this->data['SRH']['vendor_document_no']);
                if ($this->data['SRH']['retrieve_status_id'] == RS::ACCEPT_STATUS) {
                    // update CRtSH ว่ามีการ Return
                    $this->CRtSH->saveField('cust_return_status_id', CRS::RETURNED);
                } elseif ($this->data['SRH']['retrieve_status_id'] == RS::DECLINE_STATUS) {
                    $is_success &= $this->_declineReturn();
                }
            } else {
                $is_success = false;
            }

            if ($is_success) {
                $this->SRH->query("COMMIT");
                ;
            } else {
                $this->SRH->query("ROLLBACK");
                $this->passedArgs['cust_return_to_supplier_head_id'] = $this->data['SRH']['cust_return_to_supplier_head_id'];
            }
        } else {
            $this->data = null;
            return false;
        }
        return $is_success;
    }

    /**
     *
     * @return boolean decline สำเร็จหรือไม่
     */
    function _declineReturn() {
        $is_success = true;
        // update CRH ว่าไม่รับ return
        $this->CRtSH->id = $this->data['SRH']['cust_return_to_supplier_head_id'];
        $this->CRtSH->saveField('cust_return_status_id', CRS::DECLINE);

        $srh_id = $this->SRH->id;
        foreach ($this->data['SR'] as $sR) {
            // Update Cust Product Site current stock
            $retrieve_qty = $sR['retrieve_qty'];
            $cust_product_site_id = $this->CustProductSite->field('id', array('product_id' => $sR['product_id'], 'site_id' => $this->data['SRH']['site_id']));
            $this->CustProductSite->id = $cust_product_site_id;
            $current_stock = $this->CustProductSite->field('current_stock');
            $is_success &= $this->CustProductSite->saveField('current_stock', $current_stock + $retrieve_qty);

            // ดึงรายการ ITS Retrieve
            $this->SR->contain();
            $_sr = $this->SR->find('first', array(
                    'conditions' => array(
                            'SR.product_id' => $sR['product_id'],
                            'SR.supplier_retrieve_head_id' => $srh_id
                    ))
            );

            $this->ProductSerial->contain();
            $PSs = $this->ProductSerial->find('all', array(
                    'conditions' => array(
                            'cust_stock_out_id' => $sR['cust_return_to_supplier_id'],
                            'cust_stock_out_type' => CRtS::CUST_STOCK_OUT_TYPE
                    ),
                    'limit' => $retrieve_qty,
                    'order' => 'stock_out_priority'
                    )
            );

            // คัดลอก ProductSerial เดิม มาใส่อันใหม่
            for ($i = 0; $i < $retrieve_qty; ++$i) {
                // ดึงรายการ ProductSerial ที่จะ return กลับเข้ามา

                $data = array();
                $data['ProductSerial']['id'] = null;
                $data['ProductSerial']['product_id'] = $PSs[$i]['ProductSerial']['product_id'];
                $data['ProductSerial']['serial_no'] = $PSs[$i]['ProductSerial']['serial_no'];
                $data['ProductSerial']['other_information'] = $PSs[$i]['ProductSerial']['other_information'];
                $data['ProductSerial']['cost'] = $PSs[$i]['ProductSerial']['cost'];
                $data['ProductSerial']['stock_out_priority'] = $PSs[$i]['ProductSerial']['stock_out_priority'];
                $data['ProductSerial']['is_active_flag'] = true;

                $data['ProductSerial']['cust_product_site_id'] = $PSs[$i]['ProductSerial']['cust_product_site_id'];
                $data['ProductSerial']['its_stock_out_type'] = $PSs[$i]['ProductSerial']['its_stock_out_type'];
                $data['ProductSerial']['its_stock_out_id'] = $PSs[$i]['ProductSerial']['its_stock_out_id'];
                $data['ProductSerial']['cust_location_id'] = $PSs[$i]['ProductSerial']['cust_location_id'];
                $data['ProductSerial']['cust_stock_in_type'] = $PSs[$i]['ProductSerial']['cust_stock_in_type'];
                $data['ProductSerial']['cust_stock_in_id'] = $PSs[$i]['ProductSerial']['cust_stock_in_id'];
                $data['ProductSerial']['price'] = $PSs[$i]['ProductSerial']['price'];

                // update ProductSerial เดิมว่าใช้งานไม่ได้
                $this->ProductSerial->id = $PSs[$i]['ProductSerial']['id'];
                $this->ProductSerial->saveField('is_active_flag', false);

                // บันทึก ProductSerial อันใหม่
                $this->ProductSerial->create();
                $is_success &= $this->ProductSerial->save($data);
            }
        }
        return $is_success;
    }

    function view($id = null) {
        if ($id != null) {

            $this->SRH->contain(array('Customer', 'Site','CRtSH', 'Supplier', 'RS', 'SR' => array('Product' => array('Unit'), 'CustProductSite')));
            $this->data = $this->SRH->findById($id);

            $this->SRH->id = $id;
            $this->set('neighbors', $this->SRH->find('neighbors', array('fields' => array('id'),
                    'conditions' => array('SRH.supplier_id' => $this->Auth->user('supplier_id'))
                    )
                    )
            );
            $this->set('mode', 'edit');
        } else {
            // ดึงรายการ Customer Return Head ที่ยังไม่ได้ทำการ retrieve
            $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
            $this->set('crhs', $this->CRtSH->find('list', array(
                    'conditions' => array(
                            'cust_return_status_id' => CRS::RETURNING,
                            'supplier_id' => $this->Auth->user('supplier_id'),
                            'customer_id' => $customers
                    )))
            );

            if (isset($this->passedArgs['cust_return_to_supplier_head_id'])) {
                $this->CRtSH->contain(array(
                        'Customer', 'Site', 'Supplier',
                        'CRtS' => array(
                                'Product' => array('Unit'),
                                'CustProductSite',
                                'ProductSerial' => array(
                                        'fields' =>  array('DISTINCT(price)'),
                                )
                        ))
                );

                $this->data = $this->CRtSH->findById($this->passedArgs['cust_return_to_supplier_head_id']);

                if(!empty($this->data)) {
                    foreach($this->data['CRtS'] as &$cr) {
                        foreach($cr['ProductSerial'] as &$ps) {
                            $this->ProductSerial->contain();
                            $ps['return_qty'] = $this->ProductSerial->find('count', array(
                                    'group' => array('ProductSerial.price'),
                                    'conditions' => array(
                                            'cust_stock_out_id' => $ps['cust_stock_out_id'],
                                            'cust_stock_out_type' => CRtS::CUST_STOCK_OUT_TYPE,
                                            'ProductSerial.price' => $ps['price'],
                                    )
                                    )
                            );
                        }
                    }
                }
            }
            $this->set('retrieveStatuses', $this->RS->find('list'));
            $this->set('retrieve_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
            $this->set('mode', 'add');
        }

        $this->render('view');
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->SRH->contain(array('Customer', 'Site', 'CRtSH', 'Supplier', 'RS', 'SR' => array('Product' => array('Unit'), 'CustProductSite')));
        $this->data = $this->SRH->findById($id);
    }
}
?>